package com.party.mobile.biz.order.payOrder;

import com.party.common.utils.BigDecimalUtils;
import com.party.core.model.activity.Activity;
import com.party.core.model.copartner.BrokerageItem;
import com.party.core.model.distributor.DistributorRelation;
import com.party.core.model.member.Member;
import com.party.core.model.member.MemberAct;
import com.party.core.model.order.OrderForm;
import com.party.core.service.activity.IActivityService;
import com.party.core.service.member.IMemberActService;
import com.party.core.service.member.IMemberService;
import com.party.mobile.biz.activity.ActivityBizService;
import com.party.mobile.biz.analyze.MemberCopartnerDetailBizService;
import com.party.mobile.biz.copartner.BrokerageBizService;
import com.party.mobile.biz.course.CourseBizService;
import com.party.mobile.biz.distributor.DistributorBizService;
import com.party.mobile.web.dto.crowdfund.input.StatisticsInput;
import com.party.notify.notifyPush.servce.INotifySendService;
import com.party.pay.service.pay.PayOrderBizService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @ClassName CrowdfundPayOrderService
 * @Description 课程订单回调处理
 * @Author wei.li
 * @Date 2019/4/17
 **/
@Service
@Component("coursePayOrderService")
public class CoursePayOrderService extends IPayOrderService {
    Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private IActivityService activityService;
    @Autowired
    private INotifySendService notifySendService;
    @Autowired
    private PayOrderBizService payOrderBizService;
    @Autowired
    private ActivityBizService activityBizService;
    @Autowired
    private DistributorBizService distributorBizService;
    @Autowired
    private CourseBizService courseBizService;
    @Autowired
    private MemberCopartnerDetailBizService memberCopartnerDetailBizService;
    @Autowired
    private BrokerageBizService brokerageBizService;
    @Autowired
    private IMemberActService memberActService;
    @Autowired
    private IMemberService memberService;

    @Override
    public Object doMain(OrderForm orderForm) {
        // 修改活动报名状态
        activityBizService.updateMemberAct(orderForm.getId());
        // 更新活动数据
        this.updateCourseActivity(orderForm.getGoodsId(), orderForm.getPayment());
        return null;
    }

    @Override
    public void doAssist(OrderForm orderForm, Object resultObject) {
        Activity activity = activityService.get(orderForm.getGoodsId());
        MemberAct memberAct = memberActService.findByOrderId(orderForm.getId());
        Member applyMember = memberService.get(memberAct.getMemberId());
        // 课程购买成功的消息
        sendCourseMessage(orderForm, activity);
        // 处理分销的数据
        doStatistics(orderForm, memberAct, activity, applyMember);
    }

    /**
     * @param orderForm   订单
     * @param memberAct   报名
     * @param activity    活动
     * @param applyMember 报名者
     * @return
     * @Author yifeng
     * @Description 处理分销的数据
     * @Date 10:13 2019/4/19
     **/
    public void doStatistics(OrderForm orderForm, MemberAct memberAct, Activity activity, Member applyMember) {
        try {
            DistributorRelation disRelation = distributorBizService.getDistributorRelation(memberAct.getId());
            StatisticsInput input = new StatisticsInput();
            input.setOrderId(orderForm.getId());
            input.setApplyId(memberAct.getId());
            input.setPayment(orderForm.getPayment());
            input.setDistributorTargetId(orderForm.getGoodsId());
            courseBizService.statistics(input, disRelation, memberAct.getMemberId(), o -> {
                // 处理合伙人的统计数
                updateCopartnerDetail(memberAct.getId(), orderForm.getPayment(), activity, applyMember, disRelation);
                return null;
            });
        } catch (Exception e) {
            logger.error("支持数据统计分销数据异常", e);
        }
    }

    /**
     * @param memberActId 众筹id
     * @param payment     金额
     * @param activity    活动
     * @param applyMember 报名者
     * @param disRelation 分销关系
     * @return
     * @Author yifeng
     * @Description 更新合伙人数据统计
     * @Date 16:51 2019/4/18
     **/
    public void updateCopartnerDetail(String memberActId, Float payment, Activity activity,
                                      Member applyMember, DistributorRelation disRelation) {
        if (null != disRelation && distributorBizService.isCrowOrCourse(disRelation.getType())) {
            try {
                memberCopartnerDetailBizService.updateOrderAnalyze(disRelation, payment);
            } catch (Exception e) {
                logger.error("实时更新合伙人统计数异常", e);
            }
            try {
                brokerageBizService.insertBrokerageItem(disRelation, memberActId, activity,
                        BrokerageItem.TYPE_COURSE, applyMember);
            } catch (Exception e) {
                logger.error("插入分销佣金记录异常", e);
            }
        }
    }

    /**
     * @param activityId 活动id
     * @param payment    金额
     * @return
     * @Author yifeng
     * @Description 更新活动数据
     * @Date 14:10 2019/4/11
     **/
    public Activity updateCourseActivity(String activityId, Float payment) {
        Activity activity = activityService.get(activityId);

        activity.setSalesNum(activity.getSalesNum() + 1);

        Float salesAmount = BigDecimalUtils.add(activity.getSalesAmount(), payment);
        salesAmount = BigDecimalUtils.round(salesAmount, 2);
        activity.setSalesAmount(salesAmount);

        activityService.update(activity);
        return activity;
    }

    /**
     * @param orderForm 订单信息
     * @return
     * @Author yifeng
     * @Description 报名支付成功消息推送
     * @Date 14:56 2019/4/10
     **/
    public void sendCourseMessage(OrderForm orderForm, Activity activity) {
        List<String> verifyCodeList = payOrderBizService.getCouponsList(orderForm);
        for (String verifyCode : verifyCodeList) {
            try {
                notifySendService.sendCourseApply(orderForm, verifyCode, activity);
            } catch (Exception e) {
                logger.error("活动报名成功---通知报名者", e);
            }
        }
    }
}
